package cn.cdzdjd.service.impl;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;
import org.jsoup.Connection.Response;
import org.springframework.stereotype.Service;

import cn.cdzdjd.exception.ErrorCode;
import cn.cdzdjd.exception.RenException;
import cn.cdzdjd.service.UCService;
import cn.cdzdjd.util.JsoupUtil;
import cn.cdzdjd.util.UrlUtil;
import cn.cdzdjd.vo.VideoInfoVO;

@Service
public class UCServiceImpl implements UCService {
	private final String baseUrl = "https://m.uczzd.cn/iflow/api/v1/article/";
	private final String videoUrl = "https://mparticle.uc.cn/api/v2/vps?";

	@Override
	public VideoInfoVO getVideoInfo(String url) {
		System.out.println(url);
		try {
			Map<String, String> params = UrlUtil.convertUrlParamsToMap(new URL(url));
			String param = "";
			if(url.contains("video.html")||params.containsKey("video_id")) {
				if (params.get("xss_item_id") != null) {
					param = params.get("xss_item_id");
				} else {
					param = params.get("sm_article_id");
				}
				return xssItemId(param);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RenException(ErrorCode.PARSE_ERROR);
		}
		throw new RenException("不支持UC图文");
	}

	private VideoInfoVO xssItemId(String param) throws MalformedURLException {
		Response response = JsoupUtil.getUrlResponse(baseUrl + param);
		// Map<String, String> cookies = response.cookies();
		JSONObject json = new JSONObject(response.body());
		JSONObject data = json.getJSONObject("data");
		String videoTitle = data.getString("title");
		JSONObject video = data.getJSONArray("videos").getJSONObject(0);
		String poster = video.getJSONObject("poster").getString("url");
		List<String> posterList = new ArrayList<>();
		posterList.add(UrlUtil.setHttps(poster));
		if(video.getJSONObject("vposter").has("url")) {
			String vposter = video.getJSONObject("vposter").getString("url");
			posterList.add(UrlUtil.setHttps(vposter));
		}
		String ums_id = UrlUtil.convertUrlParamsToMap(new URL(data.getString("zzd_url"))).get("ums_id");
		Response videoRes = JsoupUtil.getUrlResponse(videoUrl + "ums_id=" + ums_id);
		JSONObject videoJson = new JSONObject(videoRes.body());
		List<String> videoList = new ArrayList<>();
		String videoUrl = videoJson.getJSONObject("data").getString("url");
		videoList.add(UrlUtil.setHttps(videoUrl));
		return new VideoInfoVO(videoList, posterList, videoTitle, null);
	}
}
